<template>
  <el-container>
    <el-header height="30">
      <el-button type="primary" :icon="Search" @click="handleAddNoteClick" style="width: 80%;">
        <el-icon class="el-icon--left"><Plus /></el-icon> 新建
      </el-button>
    </el-header>
    <el-main>
      <AboutProps/>
      <div>
        <el-input placeholder="输入关键字进行过滤"
                  class="w-50 m-2"
                  v-model="filterText" clearable>
          <!--          :prefix-icon="Search"  el-icon--right-->
          <template #prefix>
            <el-icon> <Search /> </el-icon>
          </template>
        </el-input>
        <el-scrollbar>
          <el-tree
              highlight-current="true"
              expand-on-click-node="false"
              ref="treeRef"
              empty-text="请先添加分类"
              node-key="id"
              indent="12"
              :data="treeData"
              :props="defaultProps"
              :filter-node-method="filterNode"
              :default-expanded-keys="default_expanded_keys"
              @node-click="handleNodeClick">
            <template #default="{ node, data }">
              <div class="custom-tree-node comp-tr-node">
                <el-icon v-if="data.type == 2"><Tickets /></el-icon>
                <span :title="node.label" class="tree-label">{{ node.label }}</span>
                <span class="comp-tr-node--btns">
                      <el-dropdown placement="bottom-start">
                        <el-icon size="18" @click.stop><Operation /></el-icon>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item @click="handleEdit(data)">
                           <el-icon size="18"><EditPen /></el-icon>重命名
                         </el-dropdown-item>
                         <el-dropdown-item @click="handleDelete(data)">
                           <el-icon size="18"><Delete /></el-icon>删除
                         </el-dropdown-item>
                         <el-dropdown-item divided="true" @click="handleRefresh()">
                           <el-icon size="18"><Refresh /></el-icon>刷新
                         </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </span>
              </div>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
    </el-main>
    <el-footer>
      <el-button type="plain" text="true" @click="handAddTypeClick">
        <el-icon class="el-icon--left"><Plus /></el-icon>新建分类
      </el-button>
    </el-footer>
  </el-container>
</template>
<script>

import {defineComponent, getCurrentInstance, onMounted, reactive, ref, toRaw, toRefs, watch} from "vue"
import AboutProps from '@/views/about-view.vue'

export default defineComponent({
  components: { AboutProps},
  setup() {
    const { proxy } = getCurrentInstance();
    const state = reactive({
      treeData: ref(proxy.$constant.treeJson),
      defaultProps: {
        children: "nodes",
        label: "text"
      },
      treeRef: [],
      default_expanded_keys: ['1'],
      //showRightMenu: false, // 右键菜单
      filterText: '',  //过滤
      curNode: null, //当前选中节点
    })

    onMounted(() => {
      getTree()
    })

    const getTree = (dirId) => {
      console.log(dirId)
    }

    watch(
        () => state.filterText, (val) => {
          toRaw(state.treeRef).filter(val)
          //toRaw(state['treeRef']).filter(val)  // 也可以
        }
    )

    //过滤数据
    const filterNode = (value, data) => {
      if (!value) return true
      return data.text.indexOf(value) !== -1
    }

    //右键 -- 编辑
    const handleEdit  = (data) => {
      proxy.$messageBox.prompt('请输入内容', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputValidator: (val) => {  // TODO 特殊字符
          if (val === null || val.length < 1 || val.length > 50) {
            return false;
          }
        },
        inputErrorMessage: '此项不能为空，最多可输入50个字符',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            //instance.confirmButtonText = 'Loading...'
            // TODO
            done()
          } else {
            done()
          }
        }
      }).then(({value}) => {
        console.log(value)
        data.text = value

        cancelSelect()
      }).catch(() => {
        cancelSelect()
      })
    }

    const handleRefresh = () => {
      console.log(state.treeData)
      state.treeData = proxy.$constant.treeJson
      console.log(state.treeData)
    }

    //右键 -- 删除
    const handleDelete = (data) => {
      //是否是目录
      if(data.nodes.length > 0) {
        proxy.$message.error("不可以删除整个目录");
        return
      } else {
        proxy.$messageBox.confirm('确认删除吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              //instance.confirmButtonText = 'loading'
              setTimeout(() => {
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
              }, 3000)
            } else {
              done()
            }
          }
        }).then(() => {
          state.treeRef.remove(data)
          proxy.$message.success("操作成功");
        }).catch(() => {
          cancelSelect()
        })
      }
    }

    //取消节点选择
    const cancelSelect = () => {
      state.curNode = undefined
    }

    //树节点点击
    const handleNodeClick = (data, node) => {
      console.log("点击节点", data, node);
      state.curNode = data
      //proxy.$bus.emit('typeId', state.curNode.id)
    }

    //添加分类
    const handAddTypeClick = () => {
      //proxy.$message("您点击了addTypeClick")
      if (state.curNode != undefined && state.curNode.depth >= 2) {
        proxy.$message.warning("不能添加超过两层");
        return;
      }
      var newNode = {
        parent_id: '',
        text: "模板组", //必须有 state.templateContent.tempName
        nodes: [],
        id: new Date().getTime(),
        typeName: "模板组",
        temporaryData: "1" //用来区分临时数据
      };
      //添加子节点
      if(state.curNode) {
        state.treeRef.append(newNode, state.curNode)
      } else if (state.curNode == undefined) {
        //没有选中的时候 添加到最外层
        newNode.depth = 1
        state.treeRef.append(newNode)
      }
      proxy.$message.success("添加分类成功");
    }

    //添加笔记
    const handleAddNoteClick = () => {
      console.log("您点击了addNoteClick,当前node=", state.curNode)
      if(!state.curNode || state.curNode == undefined || state.curNode.depth >= 2) {
        proxy.$message.warning("请先选择分类")
        return
      }
      console.log("您点击了addNoteClick.depth", state.curNode.depth)
    }

    return {
      ...toRefs(state),
      getTree,
      filterNode,
      handleNodeClick,
      handAddTypeClick,
      handleAddNoteClick,
      handleDelete,
      handleEdit,
      cancelSelect,
      handleRefresh,
    }
  }
})
</script>

<style lang="scss" scoped>
// 显示按钮
.show-btns {
  opacity: 1;
}
.el-tree {
  margin-top: 5px;
  // 自定义节点
  .comp-tr-node{
    width: 100%;
    // label
    .comp-tr-node--name{
      display: inline-block;
      line-height: 33px;
      min-height: 33px;
      // 新增
      &.is-new{
        font-weight: bold;
      }
    }
    // button
    .comp-tr-node--btns{
      opacity: 0;
    }
  }
  // 高亮显示按钮
  /*.is-current{
    &>.el-tree-node__content{
      .comp-tr-node--btns{
        @extend .show-btns;
      }
    }
  }*/
  // 悬浮显示按钮
  .el-tree-node__content {
    &:hover {
      .comp-tr-node--btns {
        @extend .show-btns;
      }
    }
  }
}

.el-header {text-align: center; margin: 0; padding: 0px; }
.el-main { overflow: hidden; padding: 12px 5px 5px 5px; }
.el-container { width: 100%; height: 96vh; display: flex; flex-direction: column;  justify-content: space-between; }
.el-footer { display: flex; height: 32px; width: 100%; }

::v-deep .el-tree-node__content { padding: 5px 0; align-items: inherit; }

.custom-tree-node i { padding: 0 0 5px 0; }
.el-dropdown { width: 20px; margin-top: 5px; }
.comp-tr-node--btns { width: 20px; display: inline; float: right; }
//.el-icon { font-size: 16px; }
.tree-label { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 115px; display: inline-block;}
</style>
